#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : config_spider
import json

import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class GuizhouDfxrmzfF676Policy(BaseTaxPolicySpider):
    name = 'guizhou_dfxrmzf_f676_policy'

    province = '贵州省'
    city = '毕节市'
    county = '大方县'
    park = ''
    source = '大方县人民政府'
    url = 'https://www.gzdafang.gov.cn/ztzl/rdzt/gzhgfxwjsjk/gfxwjsjk/dfxrmzfbgs/'
    headers = {
        "Content-Type": "application/json;charset=UTF-8",
    }

    def start_requests(self):
        yield self.Request(
            self.url,
            callback=self.return_code,
        )

    def return_code(self, response):
        tableName = response.xpath('//script').re_first(r'tableName = "(.*)"')
        if "CHNLIDs" in response.text:
            searchWord = response.xpath('//script').re_first(r'var CHNLIDs = "(\d+)"')
        else:
            searchWord = response.xpath('//input[@id="Chid"]/@value').get()

        fieldName = response.xpath('//script').re_first(r'"fieldName": "(.*)",')
        tenantId = response.xpath('//input[@id="tenantId"]/@value').get() or response.xpath('//script').re_first(r'tenantId = (\d+);')
        if "properties" in response.text:
            property = response.xpath('//script').re_first(r'"property": "(.*)",')
            value = response.xpath('//script').re_first(r'"value": "(.*)"')
            data = {"tenantId": tenantId, "tableName": tableName,
                    "sorts": [{"sortField": "save_time", "sortOrder": "DESC"}],
                    "customFilter": {"operator": "or", "properties": [{"property": property, "operator": "eq", "value": value}]},
                    "pageNo": 1, "pageSize": 10}
        else:
            data = {
                "tableName": tableName,
                "pageNo": 1,
                "pageSize": 999,
                "searchFields": [
                    {
                        "fieldName": fieldName,
                        "searchWord": searchWord
                    }
                ],
                "sorts": [
                    {
                        "sortField": "save_time",
                        "sortOrder": "DESC"
                    }
                ],
                "tenantId": tenantId,
                "isPage": True
            }
        print(data)
        url = "/irs/front/list"

        yield response.follow(
            url,
            body=json.dumps(data, separators=(',', ':')),
            headers=self.headers,
            method="POST",
            callback=self.parse_list,
            meta={'data': data}
        )

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        for elem in response.json()['data']['list']:
            item = Item()
            item['source_url'] = elem['doc_pub_url']
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem['save_time']
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            if '.html' not in item['source_url']:
                continue
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        data = response.meta.get('data')
        if response.meta.get("is_next") is not False:
            total_page = response.json()['data']['pager']['pageCount']
            for page_num in range(1, int(total_page) // 1 + 1):
                data['pageNo'] = page_num
                yield response.follow(response.url, method="POST", headers=self.headers, body=json.dumps(data, separators=(',', ':')),
                                      callback=self.parse_list, meta={'item': prev_item, 'is_next': False})

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get()
        item['content'] = response.xpath(""".""").get()
        item['province'] = self.province
        item['city'] = self.city
        item['county'] = self.county
        item['park'] = self.park
        item['source'] = self.source
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl guizhou_dfxrmzf_f676_policy".split())
